#!/bin/bash

# 引入配置文件
source config.sh

# 日志文件路径
LOG_FILE="$LOG_DIR/manage-vhost.log"

# 创建日志目录
mkdir -p $LOG_DIR
touch $LOG_FILE

# 日志记录函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | sudo tee -a $LOG_FILE
}

# 错误处理函数
error_exit() {
    log "ERROR: $1"
    exit 1
}

# Laravel 默认伪静态规则
LARAVEL_REWRITE_RULES="
location / {
    try_files \$uri \$uri/ /index.php?\$query_string;
}
"

# Vue 默认伪静态规则
VUE_REWRITE_RULES="
 
location / {
    try_files \$uri \$uri/ /index.html;
}

"

# 添加虚拟主机
add_vhost() {
    local DOMAIN=$1
    local PROJECT_DIR=$2
    local PROJECT_TYPE=$3
    local NGINX_CONF="/etc/nginx/sites-available/$DOMAIN.conf"

    log "Adding virtual host for domain: $DOMAIN..."

    if [ -f "$NGINX_CONF" ]; then
        error_exit "Virtual host for $DOMAIN already exists."
    fi

    # 根据项目类型设置伪静态规则
    if [ "$PROJECT_TYPE" == "laravel" ]; then
        REWRITE_RULES="$LARAVEL_REWRITE_RULES"
    elif [ "$PROJECT_TYPE" == "vue" ]; then
        REWRITE_RULES="$VUE_REWRITE_RULES"
    else
        error_exit "Invalid project type. Use 'laravel' or 'vue'."
    fi

    # 生成 Nginx 配置文件
    cat <<EOL | sudo tee $NGINX_CONF > /dev/null
server {
    listen 80;
    server_name $DOMAIN;
    root $PROJECT_DIR;

    index index.php index.html index.htm;

    $REWRITE_RULES

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php$PHP_VERSION-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;  # 分割请求的 URI
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param PATH_INFO \$fastcgi_path_info;  # 传递 PATH_INFO
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    error_log /var/log/nginx/${DOMAIN}_error.log;
    access_log /var/log/nginx/${DOMAIN}_access.log;
}
EOL

    # 启用虚拟主机
    sudo ln -s $NGINX_CONF /etc/nginx/sites-enabled/
    sudo nginx -t && sudo systemctl reload nginx || error_exit "Failed to reload Nginx."

    log "Virtual host for $DOMAIN added successfully."
}

# 删除虚拟主机
delete_vhost() {
    local DOMAIN=$1
    local NGINX_CONF="/etc/nginx/sites-available/$DOMAIN.conf"

    log "Deleting virtual host for domain: $DOMAIN..."

    if [ ! -f "$NGINX_CONF" ]; then
        error_exit "Virtual host for $DOMAIN does not exist."
    fi

    # 删除 Nginx 配置
    sudo rm -f /etc/nginx/sites-enabled/$DOMAIN.conf
    sudo rm -f $NGINX_CONF
    sudo nginx -t && sudo systemctl reload nginx || error_exit "Failed to reload Nginx."

    log "Virtual host for $DOMAIN deleted successfully."
}

# 主逻辑
if [ "$1" == "add" ]; then
    if [ -z "$2" ] || [ -z "$3" ] || [ -z "$4" ]; then
        error_exit "Usage: $0 add <domain> <project_directory> <project_type>"
    fi
    add_vhost $2 $3 $4
elif [ "$1" == "delete" ]; then
    if [ -z "$2" ]; then
        error_exit "Usage: $0 delete <domain>"
    fi
    delete_vhost $2
else
    echo "Usage: $0 [add|delete] <domain> <project_directory> <project_type>"
    exit 1
fi